class RegistersDescriptor():
	def __init__(self,nRegisters):
		self.registers = []
		for i in range(1,nRegisters+1):
			self.registers.append({'register':'R'+str(i),'lexemes':[]})

	def getIdxFromReg(self,register):
		regIdx = register.replace("R","")
		return int(regIdx)-1

	def addInRegister(self,register,lexeme):

		oldRegister = self.lexemeInRegister(lexeme)

		if oldRegister != None:
		# remove lexeme from old register
			self.removeLexemeFromRegister(oldRegister,lexeme)

		regIdx = self.getIdxFromReg(register)

		lexemes = self.registers[regIdx]['lexemes']

		if lexeme not in lexemes:
			lexemes.append(lexeme)


		#DEBUG
		#print "addINRegister reg:%s lex:%s"%(register,self.registers[regIdx]['lexemes'][-1])
		#print lexemes
		#FINDEBUG

	def getLexemesInRegister(self,register):
		regIdx = self.getIdxFromReg(register)
		return self.registers[regIdx]['lexemes']

	def removeLexemeFromRegister(self,register,lexeme):
		#DEBUG	
		#print "REMOVE LEXEME:",lexeme
		#DEBUG	
		regIdx = self.getIdxFromReg(register)
		self.registers[regIdx]['lexemes'].remove(lexeme)

	def removeLexemesFromRegister(self,register):
		#DEBUG	
		#print "REMOVE LEXEMES REGISTER:",register
		#DEBUG	
		regIdx = self.getIdxFromReg(register)
		self.registers[regIdx]['lexemes'] = []

	def lexemeInRegister(self,lexeme):
		for register in self.registers:
			lexemes = register['lexemes']
			if lexeme in lexemes:
				return register['register']
		return None

	def getEmptyRegister(self):
		#DEBUG	
		#print "EMPTY:",self.registers[0]
		#DEBUG	
		for i in range(len(self.registers)):
			if len(self.registers[i]['lexemes']) == 0:
				return i
		return None
	
	def getLessFullRegister(self):
		lessFullIdx = 0
		for i in range(0,len(self.registers)-1):
			if len(self.registers[i+1]['lexemes']) < len(self.registers[i]['lexemes']):
				lessFullIdx = i + 1

		return lessFullIdx

	def getNextCandidate(self):
		registerIdx = self.getEmptyRegister()
		if registerIdx == None:
			# none is empty
			registerIdx = self.getLessFullRegister()
			#print "LESS FULL REGISTER: R",registerIdx+1

		return self.registers[registerIdx]['register']

	def getSize(self):
		return len(self.registers)

	def printAll(self):
		for register in self.registers:
			print "Register:"+register['register']
			print "Lexemes:"
			for lexeme in register['lexemes']:
				print lexeme

